import axios, { type AxiosInstance, type AxiosRequestConfig } from "axios";

export class Request {

    private instance: AxiosInstance

    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config);

        this.instance.interceptors.request.use(
            (config) => {
                return config;
            }, (err) => {
                return Promise.reject(err);
            }
        );

        this.instance.interceptors.response.use(
            (res) => {
                return res.data;
            }, (err) => {
                const response = err.response;
                let result = response ? response.data : err;
                if (!result) {
                    let statusText = response.statusText
                    if (statusText) {
                        result = statusText;
                    }
                }
                return Promise.reject(result);
            }
        )
    }

    request<T = any>(config: AxiosRequestConfig): Promise<ResponseData<T>> {
        return new Promise((resolve, reject) => {
            try {

                this.instance.defaults.headers['Cache-Control'] = 'no-store'
                this.instance?.request<any, ResponseData<T>>(config).then(res => {
                    if (res.code == 200) {
                        resolve(res);
                    } else {
                        try {
                            res = res.data ? res.data : res;
                            let msg = "";
                            let errCode = res.code;
                            if (errCode === 11012) {
                                msg = "未登录，请先登录";
                            } else if (errCode === 301 || errCode === 500) {
                                msg = res.msg;
                            } else if (errCode === 11051) {
                                msg = "权限不足，请联系管理员"
                            } else {
                                msg = "程序异常，请联系管理员"
                            }
                            reject();
                        } catch (e) {
                        }
                    }
                }).catch(e => {
                    reject(e)
                })
            } catch (e) {
                reject(e);
            }
        })
    }

    POST<T = any>(config: AxiosRequestConfig) {
        config.method = 'POST';
        return this.request(config);
    }

    GET<T = any>(config: AxiosRequestConfig) {
        config.method = 'GET';
        return this.request(config);
    }
}


interface ResponseData<T = any> {
    data?: T;
    code: number;
    msg: string;
}

const _axios = new Request({
    baseURL: import.meta.env.VITE_APP_BASE_URL
})

export default _axios;